<template>
	<section>
		<!--工具条-->
		<el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
			<el-form :model="filters" :inline="true">
				<el-form-item>
					<el-input v-model="filters.keywords" placeholder="关键字" ></el-input>
				</el-form-item>
				<el-form-item>
					<el-button type="warning" v-on:click="getCourseResource">查询</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="addHandler" >新增</el-button>
				</el-form-item>
			</el-form>
		</el-col>

		<!--列表v-loading="listLoading"-->
		<el-table @row-click="rowClick" :data="courseResources" v-loading="listLoading"
				  highlight-current-row  style="width: 100%;">
			<!--多选框-->
			<el-table-column type="selection" width="55">
			</el-table-column>
			<!--索引值,为什么不用id,id不序号-->
			<el-table-column type="index" width="60">
			</el-table-column>
			<el-table-column prop="course.name" label="课程名称" width="200">
			</el-table-column>
			<el-table-column prop="resources" label="课程资源" width="200">
			</el-table-column>
			<el-table-column prop="type" label="资料类型" width="100" sortable>
				<template scope="scope">
					<span v-if="scope.row.type==0" style="color: #f7ba2a">图片</span>
					<span v-if="scope.row.type==1" style="color: #00BFFF">文件</span>
					<span v-if="scope.row.type==2" style="color: #13ce66">视频</span>
				</template>
			</el-table-column>
			<el-table-column label="操作" width="200">
				<template scope="scope">
					<el-button size="small"  @click="edit(scope.row)">编辑</el-button>
					<el-button type="danger" size="small" @click="del(scope.row)">删除</el-button>
				</template>
			</el-table-column>
		</el-table>
		<!--工具条-->
		<el-col :span="24" class="toolbar">
			<!--<el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>-->
			<el-pagination layout="prev, pager, next" @current-change="handleCurrentChange"  :page-size="5" :total="total" style="float:right;">
			</el-pagination>
		</el-col>

		<!--新增界面-->
		<el-dialog title="新增" :visible.sync="addFormVisible"  :close-on-click-modal="false">
			<el-form :model="addForm" label-width="80px"  ref="addForm">
				<el-form-item label="课程名称" prop="coursetTypId">
					<el-select v-model="addForm.courseId" filterable placeholder="请选择">
						<el-option
								v-for="item in courses"
								:key="item.id"
								:label="item.name"
								:value="item.id">
						</el-option>
					</el-select>
				</el-form-item>

				<el-form-item label="资源类型">
					<el-select v-model="addForm.type" placeholder="请选择">
						<el-option
								v-for="item in types"
								:key="item.value"
								:label="item.label"
								:value="item.value">
						</el-option>
					</el-select>
				</el-form-item>

				<el-form-item prop="resources" label="课程资料">
					<el-upload
							class="upload-demo"
							action="http://mf-mf.oss-cn-chengdu.aliyuncs.com"
							:data="uploadData"
							:before-upload="beforeUpload"
							:on-success="handleSuccess"
							:file-list="fileList"
							list-type="picture">
						<el-button size="small" type="primary">点击上传</el-button>
						<div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
					</el-upload>
				</el-form-item>

			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="addFormVisible = false">取消</el-button>
				<el-button type="primary" @click.native="addSubmit" >提交</el-button>
			</div>
		</el-dialog>
	</section>
</template>

<script>
    import { quillEditor } from "vue-quill-editor"; //调用编辑器
    import "quill/dist/quill.core.css"
    import "quill/dist/quill.snow.css"
    import "quill/dist/quill.bubble.css"

    export default {
        computed: {
            editor() {
                return this.$refs.myQuillEditor.quill
            }
        },
        components: {//使用编辑器
            quillEditor
        },
        data() {
            return {
                fileList:[],
                types: [{
                    value: '0',
                    label: '图片'
                }, {
                    value: '1',
                    label: '文件'
                }, {
                    value: '2',
                    label: '视频'
                }],
                uploadData: {  //提交到OSS的参数
                    policy: '',
                    signature: '',
                    key: '',
                    ossaccessKeyId: '',
                    dir: '',
                    host: ''
                },
                row:"",
                courseTypeProps:{
                    value:"id",
                    label:"name"
                },
                priceDisabled:true,
                courseResources:[],
                courses:[],
                addFormVisible:false,
                addForm:{
                    courseId:'',
                    resources:'',
                    type:'',
                },
                listLoading:false,
                //查询对象
                filters:{
                    keywords:''
                },
                page:1,//当前页,要传递到后台的
                total:0, //分页总数
            }
        },
        methods: {
            /*OOS三件套*/
            getUUID() {
                var s = [];
                var hexDigits = "0123456789abcdef";
                for (var i = 0; i < 36; i++) {
                    s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
                }
                s[14] = "4"; // bits 12-15 of the time_hi_and_version field to 0010
                s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
                s[8] = s[13] = s[18] = s[23] = "-";
                var uuid = s.join("");
                return uuid;
            },
            async beforeUpload(){
                await this.$http.get("/file/file/sign").then(response=>{
                    //设置相关的参数
                    var resultObj = response.data.resultObj;
                    this.uploadData.policy = resultObj.policy;
                    this.uploadData.signature = resultObj.signature;
                    this.uploadData.ossaccessKeyId = resultObj.accessid;
                    //上传的文件名，使用UUID处理一下
                    this.uploadData.key = resultObj.dir + '/'+this.getUUID()+'_${filename}';
                    this.uploadData.dir = resultObj.dir;
                    this.uploadData.host = resultObj.host;
                });
            },
            handleSuccess(res, file,fileList) {
                this.addForm.resources += this.uploadData.host + '/' + this.uploadData.key.replace("${filename}",file.name)+",";
                this.$message({message: '上传成功！', type: 'success' });

            },

            addSubmit(){
                this.$http.put("/course/courseResource",this.addForm).then(res=>{
                    var ajaxResult = res.data;
                    if(ajaxResult.success){
                        this.$message({
                            message: '提交成功!',
                            type: 'success'
                        });
                        this.addFormVisible = false;
                        this.getCourseResource();
                    }else{
                        this.$message({
                            message: '提交失败!',
                            type: 'error'
                        });
                    }
                });
            },

            getCourses(){
                this.$http.get("/course/course/").then(result=>{
                    this.courses = result.data;
                });
            },

            changeCharge(chargeId){
                console.log(chargeId);
                if(chargeId === 1){
                    this.priceDisabled = true;
                    this.addForm.price = "";
                    this.addForm.priceOld = "";
                }else{
                    this.priceDisabled = false;
                }
            },

            addHandler(){
                this.addForm={
                    courseId:'',
                    resources:'',
                    type:'',
                }
                this.fileList=[];//清空上传的图片
                this.addFormVisible = true;
            },
            edit(row){
                this.addForm=Object.assign({}, row); //数据拷贝   回显
                this.fileList=[];
                let picArr =row.resources.split(",");
                for(var i=0;i< picArr.length-1;i++){
                    console.log("picArr[i] = " + picArr[i])
                    this.fileList.push({
                        url:picArr[i]
                    })
                }
                this.addFormVisible = true;
            },

            //删除的方法  index:当前数据的行号    row:当前行数据
            del(row){
                this.$confirm('确认删除该记录吗?', '提示', {//1.删除的确认框
                    type: 'warning'
                }).then(()=>{//确认删除的按钮
                    this.listLoading = true;
                    //获取删除数据id
                    let id= row.id;
                    //发送请求 "/dept/3"
                    this.$http.delete("/course/courseResource/"+id).then(res=>{
                        this.listLoading = false;
                        console.debug(res)
                        let {success,message}=res.data;
                        if (success){
                            this.$message({
                                message: '删除成功',
                                type: 'success'
                            });
                        }else {
                            this.$message.error('网络异常');
                        }
                        //重新加载数据
                        this.getCourseResource();
                    })
                }).catch(()=>{//取消删除回调函数
                    this.$message('已取消删除');
                })
            },

            // /* 5：添加事件 */
            // selsChange(val) { //这个方法是给数据前面的选择按钮添加事件--》批量删除时
            //     this.sels = val; //val就是用户勾选的数据
            // },
            //
            // /*:6：批量删除 */
            // batchRemove() {
            //     var ids = this.sels.map(item => item.id);
            //     console.log(ids);
            //     this.$confirm('确认删除选中记录吗？', '温馨提示', {
            //         type: 'warning'
            //     }).then(() => {
            //         this.listLoading = true;
            //         this.$http.patch("/course/courseResource", ids)
            //             .then(res => {
            //                 console.log(res);
            //                 this.listLoading = false;
            //                 let {success, message} = res.data;
            //                 if (success) {
            //                     this.$message({
            //                         message: '删除成功',
            //                         type: 'success'
            //                     });
            //                 } else {
            //                     this.$message.error('网络异常');
            //                 }
            //                 this.getResource(); // 重新加载数据
            //             })
            //     }).catch(() => {
            //         this.$message({ //取消删除
            //             type: 'info',
            //             message: '已取消删除'
            //         });
            //     });
            // },

            handleCurrentChange(curentPage){
                this.page = curentPage;
                this.getCourseResource();
            },

            getCourseResource(){
                //发送Ajax请求后台获取数据  axios
                //添加分页条件及高级查询条件
                let para = {
                    "page":this.page,
                    "keyword":this.filters.keywords
                };
                this.listLoading = true; //显示加载圈
                //分页查询
                this.$http.post("/course/courseResource/list",para) //$.Post(.....)
                    .then(result=>{
                        this.total = result.data.total;
                        this.courseResources = result.data.rows;
                        this.listLoading = false;  //关闭加载圈
                    });
            },

            onLineCourse(){
                //获取选中的行
                if(!this.row || this.row  === ""){
                    this.$message({ message: '老铁，你不选中数据，臣妾上不了啊....',type: 'error'});
                    return;
                }
                this.$http.post("/course/course/onLineCourse/"+this.row.id).then(res=>{
                    var ajaxResult = res.data;
                    if(ajaxResult.success){
                        this.$message({ message: '老铁，上线成功.',type: 'success'});
                        this.getCourseResource();
                    }else{
                        this.$message({ message: ajaxResult.message,type: 'error'});
                    }
                })
            },

            offLineCourse(){
                //获取选中的行
                if(!this.row || this.row  === ""){
                    this.$message({ message: '老铁，你不选中数据，臣妾下不了啊....',type: 'error'});
                    return;
                }
                this.$http.post("/course/course/offLineCourse/"+this.row.id).then(res=>{
                    var ajaxResult = res.data;
                    if(ajaxResult.success){
                        this.$message({ message: '老铁，下线成功.',type: 'success'});
                        this.getCourseResource();
                    }else{
                        this.$message({ message: ajaxResult.message,type: 'error'});
                    }
                })
            },

            rowClick(row){
                this.row = row;
                console.log(this.row);
            },

            statusFormatter: function (row, column) {
                return row.status == 1 ? '已上线' : '未上线';
            },
        },

        mounted() {
            this.getCourseResource(); // 获取课程资源列表信息
            this.getCourses(); // 获取课程下拉信息
        }
    }

</script>
